Home:ALL Converter>Stack using linked list in C, freeing temp_node in pop function but still want to return it

Stack using linked list in C, freeing temp_node in pop function but still want to return it

Ask Time:2021-10-01T23:41:57         Author:pzii22

Json Formatter

I am implementing a stack using linked list in C, and I stumbled upon two issues:

  1. I need the stack_pop function to return a valid value temp, that is the temporary node/cell, and therefore, I can't free it. So, 1) Do you think freeing each node for every pop function call is better than until the end using the stack_destroy() 2) How can I achieve both, free(temp) and return it at the same time in stack_pop?

  2. How bad my implementation becomes not using exit(1) in both stack_push and stack_pop functions?

This is the implementation:

//// Stack

// Linked list
typedef struct {
    int data;
    Cell* next;
} Cell;

struct stack_l {
    size_t count;
    Cell *top;
};
typedef struct stack_l *Stack;

Author:pzii22,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/69408598/stack-using-linked-list-in-c-freeing-temp-node-in-pop-function-but-still-want-t
dbush :

You've got stack_pop declared to return an int, but you're attempting to return a Cell * which doesn't make sense.\nCopy the value in the popped cell to a local variable, free the popped cell, then return the value.\n temp = stack->top;\n stack->top = stack->top->next;\n temp->next = NULL;\n stack->count--;\n int val = temp.data;\n free(temp)\n return val;\n\nAlso, it makes no sense to call exit in either stack_push or stack_pop as that ends the program.",
2021-10-01T15:50:54
yy